import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';
// import XLSXStyle from 'xlsx-style';

/**
* @description 前端导出excel
* @param {String} fileName 文件名
* @param {Array} tableHeader 表头
* @param {Array} tableData 表数据
* @return void
*/
export let tableToExcel = ({ fileName, tableHeader, tableData }) => {

    // 用于替换数据中的换行符，是其可以在单元格内正常显示
    const wrapMark = '<br style="mso-data-placement:same-cell;"/>',

        // 设置单元格数据显示为文本格式，避免过大的数字以科学计数法的形式显示
        tdTagHeader = '<td style="mso-number-format:\'\\@\';font-size:14.67px;width:150px;font-family:Calibri;text-align:center;vertical-align:bottom;white-space: nowrap; word-break: keep-all;">';

    let dataStr = '<tr>'

    tableHeader.forEach(item => {
        dataStr += `<td style="width:100px;border:.5px solid rgb(0,0,0);mso-number-format:'\\@';color:rgb(0,0,0);font-family:'宋体';font-weight:bold;font-size:20px;white-space: nowrap; word-break: keep-all;background-color:rgb(192, 192, 192);text-align:center;">${item.label}</td>`;
    })

    dataStr += '</tr>';
    tableData.forEach(item => {
        dataStr += '<tr>'
        tableHeader.forEach(key => {
            // 这种方式本质是导出 html 文件，html 中连续的空格符会被合并成一个显示
            // replace(/ /g, '&nbsp;') 将空格符替换成 &nbsp; 使其可以正常显示
            dataStr += tdTagHeader + `${item[key.prop]}`.replace(/ /g, '&nbsp;').replace(/\n/g, wrapMark) + '</td>';
        });
        dataStr += '</tr>'
    })

    // 设置 Worksheet 名
    const workSheet = 'Sheet1',

        template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
        xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
        <head><meta charset="UTF-8" />
        <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${workSheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/>
        </x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${dataStr}</table></body></html>`,

        url = 'data:application/vnd.ms-excel;base64,' + window.btoa(unescape(encodeURIComponent(template))),
        link = document.createElement('a');

    link.href = url;
    link.download = fileName + '.xlsx';
    link.style.display = 'none';
    link.click();


}


// 根据dom导出表格
export let exportToExcel = (selector, fileName) => {
    const wb = XLSX.utils.table_to_book(document.querySelector(selector), {
            raw: true
        }),
        wbout = XLSX.write(wb, {
            bookType: 'xlsx',
            bookSST: false,
            type: 'array'
        });
    try {
        FileSaver.saveAs(
            new Blob([wbout], { type: 'application/octet-stream' }),
            fileName + '.xlsx'
        );
        this.$message.success('导出成功'); // 导出成功的提示
    } catch (e) {
        if (typeof console !== 'undefined') { console.log(e, wbout); }
    }
    return wbout;
}